<?php

namespace app\admin\controller;

use app\helper\CacheHelper;
use think\admin\Controller;
use think\admin\helper\QueryHelper;
use think\admin\model\SystemSites;
use \PhpOffice\PhpSpreadsheet\IOFactory;

/**
 * 站点配置
 * @class Sites
 * @package app\admin\controller
 */
class Sites extends Controller
{
    /**
     * 站点配置
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        SystemSites::mQuery()->layTable(function () {
            $this->title = '站点配置';
        }, static function (QueryHelper $query) {

        });
    }

    /**
     * 列表数据处理
     * @param array $data
     * @throws \Exception
     */
    protected function _index_page_filter(array &$data)
    {
        // foreach ($data as &$vo) try {
        //   $vo['type'] == 1 ? $vo['type'] = 'QB' : $vo['type'] = 'TR';
        //   $vo['is_skip_hash'] == 1 ? $vo['is_skip_hash'] = '跳过' : $vo['is_skip_hash'] = '不跳过';
        //   $vo['is_paused'] == 1 ? $vo['is_paused'] = '是' : $vo['is_paused'] = '否';
        // } catch (\Exception $exception) {
        //     $vo['geoip'] = $exception->getMessage();
        // }
    }

    /**
     * 删除站点
     * @auth true
     */
    public function remove()
    {
        $this->clearcachebyid();

        SystemSites::mDelete();
    }

    /**
     * 编辑站点
     * @auth true
     */
    public function edit()
    {
        // 编辑保存时处理
        if (!($this->request->isGet())) {
            $id = $this->request->post('id');
            if (!$id) {
                $this->error("失败，参数缺失");
            }

            $site_url = $this->request->param()['site_url'];
            $site = SystemSites::mQuery()->db()->where('id', $id)->find();
            // 若变更了站点地址，则需清理缓存
            if ($site && $site['site_url'] != $site_url) {
                CacheHelper::ClearPiecesHash($site['site_url']);
            }
        }

        SystemSites::mForm('edit');
    }
    /**
     * 添加站点
     * @auth true
     */
    public function add()
    {
        SystemSites::mForm('add');
    }

    /**
     * 清空站点缓存
     * @auth true
     */
    public function clearcache()
    {
        $all = $this->request->get('all');
        if ($all) {
            CacheHelper::ClearAllPiecesHash();
            $this->success("成功");
        }

        $this->clearcachebyid();
        $this->success("成功");
    }

    /**
     * 清空站点缓存
     * @return void
     */
    private function clearcachebyid()
    {
        $id = $this->request->post('id');
        if (!$id) {
            $this->error("失败，参数缺失");
        }

        $sites = SystemSites::mQuery()->db()->where('id', 'in', $id)->select();
        foreach ($sites as $site) {
            CacheHelper::ClearPiecesHash($site['site_url']);
        }
    }

    /**
     * 导入站点配置
     * @return void
     */
    public function import()
    {
        $file = $this->app->request->post('file');
        if (!$file) {
            $this->error('文件不能为空');
        }

        $file = 'public/' . str_replace($this->app->request->domain(), '', $file);
        //表格字段对应
        $cellName = [
            'A' => 'id', //ID
            'B' => 'site_name', //站点名称
            'C' => 'site_url', //站点地址
            'D' => 'api_url', //站点接口地址
            'E' => 'passkey', //站点passkey
            'F' => 'request_interval', //站点请求间隔
            'G' => 'upload_limit', //站点上传限速
            'H' => 'download_limit', //站点下载限速
        ];
        //加载文件
        $spreadsheet = IOFactory::load($file);

        $sheet = $spreadsheet->getActiveSheet(); // 获取表格
        $highestRow = $sheet->getHighestRow(); // 取得总行数
        $sheetData = [];
        for ($row = 2; $row <= $highestRow; $row++) { // $row表示从第几行开始读取
            foreach ($cellName as $cell => $field) {
                $value = $sheet->getCell($cell . $row)->getValue();
                $value = trim($value);
                $sheetData[$row][$field] = $value;
            }
            $flag = $this->app->db->name('system_sites')->where('site_url', $sheetData[$row]['site_url'])->find();
            if (!$flag) {
                $this->app->db->name('system_sites')->data($sheetData[$row])->insert();
            } else {
                $this->app->db->name('system_sites')->data($sheetData[$row])->update();
            }
        }
        // $sheetData = array_values($sheetData);
        // $count = count($sheetData);
        // //TO DO 入库
        // $this->app->db->name('system_sites')->data($sheetData)->strict(false)->insertAll();
        $this->success('导入成功');
    }
}
